import { fileURLToPath, URL } from 'node:url'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
// import vueDevTools from 'vite-plugin-vue-devtools'
import * as path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { visualizer } from 'rollup-plugin-visualizer'
import autoprefixer from 'autoprefixer'
import cssnano from 'cssnano'
import litePreset from 'cssnano-preset-lite'
import { name } from './package.json'
// env变量
const env = loadEnv('development', process.cwd())
//
const FPI_ASSETS_VERSION = '1.0.0'

// https://vite.dev/config/
export default defineConfig({
    define: {
        __APP_FPI_ASSETS_VERSION__: JSON.stringify(FPI_ASSETS_VERSION),
    },

    base: process.env.NODE_ENV === 'production' ? `/${name}/` : '/',

    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url)),
        },
    },

    server: {
        port: 3089,
        open: true,
        proxy: {
            '/api': {
                target: env.VITE_API_URL,
                rewrite: path => path.replace(/^\/api/, ''),
                changeOrigin: true,
                secure: false,
            },
        },
    },

    plugins: [
        vue({
            template: {
                compilerOptions: {
                    isCustomElement: tag => /^micro-app/.test(tag),
                },
            },
        }),
        // devTools
        // vueDevTools(),
        // 自动导入
        AutoImport({
            resolvers: [ElementPlusResolver({ importStyle: false })],
            imports: ['vue', 'vue-router', 'pinia'],
            dts: 'auto-imports.d.ts',
            eslintrc: {
                enabled: false,
                filepath: '.eslintrc-auto-import.json',
                globalsPropValue: true,
            },
        }),
        // 自动导入组件 目前只导入ElementPlus
        Components({
            dirs: [],
            resolvers: [ElementPlusResolver({ importStyle: false })],
        }),
        // svg插件
        createSvgIconsPlugin({
            iconDirs: [path.resolve(process.cwd(), 'src/assets/svg-icons')],
            symbolId: '[name]',
        }),
        // 打包分析插件
        visualizer({
            filename: 'dist/stats.html',
        }),
    ],

    build: {
        target: ['chrome78'],
        minify: true,
        cssMinify: false, // 必须为false
    },

    css: {
        preprocessorOptions: {
            scss: { api: 'modern-compiler' },
        },
        //
        postcss: {
            plugins: [
                // 配合 cssMinify:false 相当于重写的css压缩方式，否则会移除css注释
                cssnano({
                    preset: litePreset({ discardComments: false }),
                    plugins: [autoprefixer],
                }),
            ],
        },
    },
})
